package com.zm.demo.shoppingmall.gateway;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author z01140
 * @Package: com.zm.demo.shoppingmall.gateway
 * @Description:
 * @CreateDate 2022/4/28 17:05
 * @UpdateDate 2022/4/28 17:05
 */
@Slf4j
public class ExcelExportDemo {


    public static void main(String[] args) throws IOException {

        CsvReader csvReader = new CsvReader(CsvReadConfig.defaultConfig());
        // 此方法必须包含标题
        csvReader.setContainsHeader(true);
        AtomicInteger count = new AtomicInteger();
        AtomicInteger totalRows = new AtomicInteger();
        //插入操作的list
        List<List<String>> rows = new ArrayList<>();
        List<Map<String, String>> rowsMap = new ArrayList<>();
        //更新操作的list
        List<List<String>> updateRows = new ArrayList<>();
        Map<String, BigDecimal> custPrincipal = new HashMap<>();
        String localFileDir = "D:\\zm\\工作\\07\\法催\\0716";
        try (Reader reader = new FileReader(localFileDir + File.separator + "订单数据.txt")){
            csvReader.read(reader, (row) -> {
                Map<String, String> titleToContentMap =  row.getFieldMap();
                String id = titleToContentMap.get("借款人身份证号");
                if (StringUtils.isNotBlank(id)){
                    custPrincipal.put(id, custPrincipal.getOrDefault(id, BigDecimal.ZERO).add(new BigDecimal(titleToContentMap.get("归户金额"))));
                    rowsMap.add(titleToContentMap);
                    List<String> rawList = row.getRawList();
                    rows.add(rawList);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        for (List<String> row : rows) {
            row.set(15, custPrincipal.get(row.get(20)).toString());
        }


        createLocalCsvFileWithList(rows, localFileDir, "诉讼材料数据表-" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".csv");

    }

    public static void createLocalCsvFileWithList(List<List<String>> list, String localFileDir, String fileName) throws IOException {
        String localFilePath = localFileDir + File.separator + fileName;
        try (CsvWriter csvWriter = new CsvWriter(localFilePath, Charset.forName("UTF-8"), Boolean.TRUE)){
            csvWriter.write(list);
            log.info("csv文件生成成功，文件路径：{}", localFilePath);
        }catch (Exception e){
            throw new RemoteException(String.format("生成CSV文件%s失败。", localFilePath), e);
        }
    }

}
